package com.yatong.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yatong.commons.util.ExcelUtil;
import com.yatong.commons.util.ExportUtil;
import com.yatong.commons.util.PageData;
import com.yatong.entity.Company;
import com.yatong.service.CompanyService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: YaTong
 * @description: 公司资料(Company)表控制层
 * @author: Mr.Guo
 * @create: 2018-09-21 17:43:27
 **/
@Controller
@RequestMapping("/company")
public class CompanyController {

//    @Value("${file.uploadFolder}")
//    private String uploadFolder;

    /**
     * 服务对象
     */
    @Autowired
    private CompanyService companyService;

    /**
     * 访问企业信息首页
     * @param model
     * @return
     */
    @RequestMapping("/")
    public String company_index(Model model){
        return "company/company_list";
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/selectOne")
    public Company selectOne(Integer id) {
        return this.companyService.queryById(id);
    }

    /**
     * 通过查询条件查询多条数据
     *
     * @param company
     * @return
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public Object queryAll(Company company,@RequestParam Map<String, String> params,
                           @RequestParam(required = false) String param1,
                           @RequestParam(required = false) String param2,
                           @RequestParam(required = false) String param3){

        PageHelper.startPage(Integer.parseInt(params.get("pageNumber")), Integer.parseInt(params.get("pageSize")));
        company.setCompanyName(param1);
        company.setAddress(param2);


        List<Company> companies = this.companyService.queryAll(company,param3);

        PageInfo<Company> page = new PageInfo<Company>(companies);
        return new PageData().ResultMap(page);
    }

//    @RequestMapping("/export")
//    @ResponseBody
//    public Object export(HttpServletRequest request, HttpServletResponse response,
//                         Company company, @RequestParam(required = false) String companyName,
//                         @RequestParam(required = false) String address) throws IOException {
//
//        company.setCompanyName(companyName);
//        company.setAddress(address);
//        List<Company> companies = this.companyService.queryAll(company);
//
//
//        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
//        for (int i =0;i < companies.size(); i++){
//            Map<String,String> map = new HashMap<String,String>();
//            map.put("id",String.valueOf(i));
//            map.put("companyName",companies.get(i).getCompanyName());
//            map.put("address",companies.get(i).getAddress());
//            map.put("contacts",companies.get(i).getContacts());
//            map.put("telePhone",companies.get(i).getTelePhone());
//            map.put("mobilePhone",companies.get(i).getMobilePhone());
//            map.put("type",companies.get(i).getType());
//            list.add(map);
//        }
//
//        // 开始导出
//        ExportUtil exportUtil = new ExportUtil();
//        exportUtil.setFileLoaclPath("E:/company.xls");
//        exportUtil.init();
//        exportUtil.export(list,"20181018");
//        exportUtil.generate("/uploadFolder/company1.xls");
//        return "成功";
//    }

    @RequestMapping("/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response,Company company,
                       @RequestParam(required = false) String companyName,
                       @RequestParam(required = false) String address,
                       @RequestParam(required = false) String tuijian) throws IOException {
        company.setCompanyName(companyName);
        company.setAddress(address);

        List<Company> companies = this.companyService.queryAll(company,tuijian);

        //excel标题
        String[] title = {"企业名称","企业地址","联系人","固话","手机号","类型"};
        //excel文件名
        String fileName = "企业信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "企业信息列表";
        String [][] content = new String[companies.size()][];

        for (int i = 0; i < companies.size(); i++) {
            content[i] = new String[title.length];
            Company obj = companies.get(i);
            if(obj.getCompanyName() !="" && obj.getCompanyName() != null)
                content[i][0] = obj.getCompanyName().toString();
            if(obj.getAddress() !="" && obj.getAddress() != null)
                content[i][1] = obj.getAddress().toString();
            if(obj.getContacts() !="" && obj.getContacts() != null)
                content[i][2] = obj.getContacts().toString();
            if(obj.getTelePhone() !="" && obj.getTelePhone() != null)
                content[i][3] = obj.getTelePhone().toString();
            if(obj.getMobilePhone() !="" && obj.getMobilePhone() != null)
                content[i][4] = obj.getMobilePhone().toString();
            if(obj.getType() !="" && obj.getType() != null)
                content[i][5] = obj.getType().toString();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            ExcelUtil.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
            System.out.println("导出成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 访问新增公司页
     * @param model
     * @return
     */
    @RequestMapping("/company_add")
    public String company_add(Model model){
        return "company/company_add";
    }


    /**
     * 保存新增公司
     * @param model
     * @return
     */
    @RequestMapping("/company_save")
    @ResponseBody
    public String company_save(Company company,Model model){
        String flag = "0";
        Company insert = companyService.insert(company);
        if (insert != null)
            flag = "1";
        return flag;
    }


    /**
     * 访问编辑企业信息页
     * @param model
     * @return
     */
    @RequestMapping("/company_edit")
    public String company_edit(@RequestParam(required = false) String id,Model model){
        Company company = companyService.queryById(Integer.parseInt(id));
        model.addAttribute("company",company);
        return "company/company_edit";
    }



    /**
    * 修改企业信息
    * @param model
    * @return
    */
    @RequestMapping("/company_update")
    @ResponseBody
    public int company_update(Company company,Model model){
        int flag = 0;

        Company thisCompany = companyService.queryById(company.getId());
        thisCompany.setCompanyName(company.getCompanyName());
        thisCompany.setAddress(company.getAddress());
        thisCompany.setContacts(company.getContacts());
        thisCompany.setTelePhone(company.getTelePhone());
        thisCompany.setMobilePhone(company.getMobilePhone());
        thisCompany.setIntentionalTime(company.getIntentionalTime());

        flag = companyService.update(thisCompany);
        return flag;
    }
    /**
     * 修改企业状态
     * @return
     */
    @RequestMapping("/update_stats")
    @ResponseBody
    public int update_stats(Company company,@RequestParam(required = false) String id,
                                @RequestParam(required = false) String stats,@RequestParam(required = false) String intentionalTime){
        int flag = 0;
        company.setId(Integer.parseInt(id));
        company.setPhoneState(stats);
        if (intentionalTime != "" && intentionalTime != null){
            company.setIntentionalTime(intentionalTime);
        }
        flag = companyService.update(company);
        return flag;
    }


}